<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android,Note," />





  <link rel="alternate" href="/atom.xml" title="GrantonZhuang's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="Android 开发中，加载图片的一些代码笔记。">
<meta property="og:type" content="article">
<meta property="og:title" content="Android 加载图片开发笔记">
<meta property="og:url" content="https://grantonzhuang.github.io/2016/10/29/AndroidBitMapNote/index.html">
<meta property="og:site_name" content="GrantonZhuang's Blog">
<meta property="og:description" content="Android 开发中，加载图片的一些代码笔记。">
<meta property="og:updated_time" content="2016-10-29T15:19:48.600Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android 加载图片开发笔记">
<meta name="twitter:description" content="Android 开发中，加载图片的一些代码笔记。">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="https://grantonzhuang.github.io/2016/10/29/AndroidBitMapNote/"/>

  <title> Android 加载图片开发笔记 | GrantonZhuang's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">GrantonZhuang's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Android 加载图片开发笔记
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-10-29T23:11:17+08:00" content="2016-10-29">
              2016-10-29
            </time>
          </span>

          

          
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Android 开发中，加载图片的一些代码笔记。</p>
<a id="more"></a>
<h2 id="计算源图片宽高"><a href="#计算源图片宽高" class="headerlink" title="计算源图片宽高"></a>计算源图片宽高</h2><p>图片源文件和目标 View 之间，大部分情况下，不会完全地等宽等高，所以需要对图片进行压缩。</p>
<p>压缩图片需要用到 <code>BitmapFactory.Options</code>，具体用法如下。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">BitmapFactory.Options options = <span class="keyword">new</span> BitmapFactory.Options();</div><div class="line">options.inJustDecodeBounds = <span class="keyword">true</span>;</div><div class="line"><span class="comment">// decodeFile() 方法的参数很多，接收不同的图片来源。</span></div><div class="line">BitmapFactory.decodeFile(file.getAbsolutePath(), options);</div><div class="line"><span class="comment">// 源图片的高度和宽度</span></div><div class="line"><span class="keyword">int</span> sourceHeight = options.outHeight;</div><div class="line"><span class="keyword">int</span> sourceWidth = options.outWidth;</div></pre></td></tr></table></figure>
<p>其中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">options.inJustDecodeBounds = <span class="keyword">true</span>;</div></pre></td></tr></table></figure>
<p>设置为 inJustDecodeBounds 为 true 表示不把整个图片加载进内存中，只是测量其宽高，MIME TYPE 等信息。</p>
<h2 id="计算压缩比例"><a href="#计算压缩比例" class="headerlink" title="计算压缩比例"></a>计算压缩比例</h2><p>如果目标的 View 比源图片小，就需要对图片进行压缩，可以通过以下代码片段计算出缩放比例。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (sourceHeight &gt; targetHeight || sourceWidth &gt; targetWidth) &#123;</div><div class="line">    <span class="keyword">int</span> heightRatio = Math.round((<span class="keyword">float</span>) sourceHeight / (<span class="keyword">float</span>) targetHeight);</div><div class="line">    <span class="keyword">int</span> widthRatio = Math.round((<span class="keyword">float</span>) sourceWidth / (<span class="keyword">float</span>) targetWidth);</div><div class="line">    options.inSampleSize = Math.max(heightRatio, widthRatio);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>计算出 inSampleSize 之后，不再需要测量图片，而是要加载图片，将 inJustDecodeBounds 设置为 false</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">options.inJustDecodeBounds = <span class="keyword">false</span>;</div></pre></td></tr></table></figure>
<p>编码图片，这里的 inSampleSize 只会取最近的一个 2 的整数次幂（向下取整），比如计算出来的 inSampleSize 是 7，那么实际上是 4.</p>
<p>也就是宽和高同时除以 2，整个面积变为原来的 1/4.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">FileInputStream fileInputStream = <span class="keyword">new</span> FileInputStream(file);</div><div class="line">BufferedInputStream bufferedInputStream = <span class="keyword">new</span> BufferedInputStream(fileInputStream);</div><div class="line"><span class="keyword">return</span> BitmapFactory.decodeStream(bufferedInputStream, <span class="keyword">null</span>, options);</div></pre></td></tr></table></figure>
<p>这样子编码出来的 bitmap 对象，所占的内存就是参照 目标 View 计算出来的，相对合理。</p>
<h2 id="再次压缩图片"><a href="#再次压缩图片" class="headerlink" title="再次压缩图片"></a>再次压缩图片</h2><p>由于 inSampleSize 参数的限制，所以，压缩后的图片不一定是效果最好的（一般情况下都不是），这个时候， bitmap 所占的内存已经比较小了，可以使用 createScaleBitmap 方法再次进行缩放，这个操作是 bitmap 上进行操作的，所以压缩返回新对象之后，需要将原来的 bitmap 对象回收。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> Bitmap <span class="title">createScaleBitmap</span><span class="params">(Bitmap src, <span class="keyword">int</span> targetWidth, <span class="keyword">int</span> targetHeight)</span> </span>&#123;</div><div class="line">    Bitmap dst = Bitmap.createScaledBitmap(src, targetWidth, targetHeight, <span class="keyword">false</span>);</div><div class="line">    <span class="keyword">if</span> (src != dst) &#123;</div><div class="line">        src.recycle();</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> dst;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="获取-View-的宽高"><a href="#获取-View-的宽高" class="headerlink" title="获取 View 的宽高"></a>获取 View 的宽高</h2><p>获取 View 的宽高时候，可能会出现取值为 0 的情况，出现这种情况，可能的原因是：整个 ViewTree 并没有绘制完成。</p>
<p>参考一个 stackoverflow 上的<a href="http://stackoverflow.com/questions/8170915/getheight-returns-0-for-all-android-ui-objects" target="_blank" rel="external">回答</a>，对 ViewTree 进行监听，当绘制完成之后，再获取 View 的宽高。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">final</span> TextView tv = (TextView)findViewById(R.id.venueLabel);</div><div class="line"><span class="keyword">final</span> ViewTreeObserver observer= tv.getViewTreeObserver();</div><div class="line">observer.addOnGlobalLayoutListener(<span class="keyword">new</span> OnGlobalLayoutListener() &#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onGlobalLayout</span><span class="params">()</span> </span>&#123;</div><div class="line">        tv.getHeight();</div><div class="line">        observer.removeGlobalOnLayoutListener(<span class="keyword">this</span>);</div><div class="line">    &#125;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag">#Android</a>
          
            <a href="/tags/Note/" rel="tag">#Note</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/10/22/ViewSQLite/" rel="next" title="Android SQLite 工具记录">
                <i class="fa fa-chevron-left"></i> Android SQLite 工具记录
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://ww1.sinaimg.cn/mw690/6e8939a6gw1f3g1u1mc6lj20hs0hsmxf.jpg"
               alt="Granton Zhuang" />
          <p class="site-author-name" itemprop="name">Granton Zhuang</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives/index.html">
              <span class="site-state-item-count">26</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#计算源图片宽高"><span class="nav-number">1.</span> <span class="nav-text">计算源图片宽高</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#计算压缩比例"><span class="nav-number">2.</span> <span class="nav-text">计算压缩比例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#再次压缩图片"><span class="nav-number">3.</span> <span class="nav-text">再次压缩图片</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#获取-View-的宽高"><span class="nav-number">4.</span> <span class="nav-text">获取 View 的宽高</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Granton Zhuang</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  




  
  

  

  

  

</body>
</html>
